/* 
 * Copyright (C) 2010 Christian Schneider
 * 
 * This file is part of NS2 news.
 * 
 * NS2 news is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NS2 news is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NS2 news.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package tritop.android.naturalselectionnews;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class StatsWorker extends Thread implements IGLOBALS{
	public static final int WARSTATSPARSER=1;
	public static final int KILLSTATSPARSER=2;
    private static final int CON_TIMEOUT=5*1000;
    private static final String LOGTAG="StatsWorker";
	private URL url;
	private DBHelper dbHelper;
	private int jsonType;
	private Handler mHandler=null;
	
	StatsWorker(URL url,int jsonType, DBHelper dbh,Handler handler){
		this.url = url;
		this.dbHelper=dbh;
		this.jsonType=jsonType;
		this.mHandler=handler;
	}
	
	@Override
	public void run() {
		if(DEBUG_ON){
			Log.e("LOGTAG","Stats worker started type "+jsonType);
		}
		switch(jsonType){
			case WARSTATSPARSER:parseWarJSON(downloadJSON());break;
			case KILLSTATSPARSER:parseKillJSON(downloadJSON());break;
			default:break;
		}
		Message msg=mHandler.obtainMessage(WorkManager.STATSWORKERMSGID, 1, 1);
		mHandler.sendMessage(msg);
	}

	private String downloadJSON(){
		try {
			StringBuilder sBuilder= new StringBuilder();
			String line=null;
			
			URLConnection con = url.openConnection();
			con.setConnectTimeout(CON_TIMEOUT);
			BufferedReader bReader = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8"));
			
			while((line = bReader.readLine()) !=null){
				sBuilder.append(line);
			}
			
			return sBuilder.toString();
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	
	private boolean parseWarJSON(String json){
		if(json!=null){
			try {
				JSONArray jsonArray = new JSONArray(json);
				synchronized(dbHelper){
				dbHelper.beginBulkWork();
				for(int i=0;i<jsonArray.length();i++){
					JSONObject obj=jsonArray.getJSONObject(i);
					long date         =    obj.getLong(DBHelper.WAR_STATS_DATA_DATE);
					String map       =    obj.getString(DBHelper.WAR_STATS_DATA_MAP);
					double length    =    obj.getDouble(DBHelper.WAR_STATS_DATA_LENGTH);
					int winner       =    obj.getInt(DBHelper.WAR_STATS_DATA_WINNER);
					double version   =    obj.getDouble(DBHelper.WAR_STATS_DATA_VERSION);
					dbHelper.insertBulkWarStatsValues(date, map, length, winner, version);
				}
				dbHelper.endBulkWork();
				}
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
	
	private boolean parseKillJSON(String json){
		if(json!=null){
			try {
				JSONArray jsonArray = new JSONArray(json);
				synchronized(dbHelper){
				dbHelper.beginBulkWork();
				for(int i=0;i<jsonArray.length();i++){
					JSONObject obj=jsonArray.getJSONObject(i);
					dbHelper.insertBulkKillStatsValues(obj);
				}
				dbHelper.endBulkWork();
				}
				return true;
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
	
	
	
}
